//
//  LJTabbarController.swift
//  LJWeibo
//
//  Created by 连俊杨 on 2017/10/6.
//  Copyright © 2017年 yang_ljun. All rights reserved.
//

import UIKit
import SVProgressHUD
class LJTabbarController: UITabBarController {
    /// 这个button方法：图片和背景图片
    fileprivate lazy var composeButton: UIButton = UIButton.cz_imageButton(
        "tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    /// 定时器
    fileprivate var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        setupComposeButton()
        setupStatusTimer()
        
        /// 欢迎视图或者新特性视图
        setupNewFeatrueView()
        
        /// 导航控制器代理
        delegate = self
        
        /// 添加接收登录操作的通知
        NotificationCenter.default.addObserver(self, selector: #selector(userShouldLogin), name: NSNotification.Name(rawValue: UserShouldLoginNotification), object: nil)
    }
    
    /// 让当前tabbarController以及它的子控制器都只支持竖屏
    /// 就是说所有视图都是按照竖屏布局的，横过来不会有变化
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    
    /// MARK: 事件处理
    @objc fileprivate func userShouldLogin(n: Notification) {
        /// 跳转之前做提示
        var when = DispatchTime.now()
        
        if n.userInfo != nil {
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录已经过期，请重新登录!")
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            SVProgressHUD.setDefaultMaskType(.clear)
            /// 跳转
            let nav = UINavigationController(rootViewController: LJOAuthViewController())
            self.present(nav, animated: true, completion: nil)
        }
    }
    
    /// @objc 能够让私有的方法通过OC的方式访问，即运行时的消息机制访问
    @objc fileprivate func composeStatus() {
        
        print("撰写微博")
    }
}


// MARK: - 新特性或者欢迎视图
extension LJTabbarController {
    
    fileprivate func setupNewFeatrueView() {
        if !LJNetworkManager.sharedManager.userLogin {
            return
        }
        /// 根据版本号创建视图
        let v = isNewVersion ? LJNewfeatureView.newFeatureView() : LJWelcomeView.welcomeView()
        
        view.addSubview(v)
    }
    
    fileprivate var isNewVersion: Bool {
        
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        
        let path: String = ("version" as NSString).cz_appendDocumentDir()
        let sandboxVersion = (try? String(contentsOfFile: path)) ?? ""
        
        /// 保存当前版本到沙盒
        _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        return currentVersion != sandboxVersion
    }
}


// MARK: - 读取未读微博定时器
extension LJTabbarController {
    func setupStatusTimer() {
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(setupNumber), userInfo: nil, repeats: true)
    }
    
    /// 设置budgeNumber
    @objc private func setupNumber() {
        LJNetworkManager.sharedManager.unReadCount { (count) in
            
            if !LJNetworkManager.sharedManager.userLogin {
                return
            }
            
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

// MARK: - UITabBarControllerDelegate 用于解决tabbar点击控制
extension LJTabbarController: UITabBarControllerDelegate {
    
    /// tabbar控制器将要选择目标控制器
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController description
    ///   - viewController: 将要目标控制器
    /// - Returns: 是否返回
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        let idx = (childViewControllers as NSArray).index(of: viewController)
        let currentSecIdx = selectedIndex
        
        if currentSecIdx == 0 && idx == 0 {
            let nav = childViewControllers[0] as! UINavigationController
            let vc  = nav.childViewControllers[0] as! LJHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                vc.loadData()
            })
            
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }
}

extension LJTabbarController {
    
    /// 添加撰写微博按钮
    fileprivate func setupComposeButton() {
        tabBar.addSubview(composeButton)
        
        /// 位置缩进
        let count: CGFloat = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count
        
        /// insetBy: 这个方法返回CGRect
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    /// 添加子视图控制器
    fileprivate func setupChildControllers() {
        /// 这个信息字典先从沙盒加载，如何没有就从bundle加载
        let jsonDoc = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (jsonDoc as NSString).appendingPathComponent("main.json")
        
        var data = NSData(contentsOfFile: jsonPath)
        
        if data == nil {
            let bundlePath = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: bundlePath!)
        }
        
        /// 代码到此，data一定有数据
        /// 反序列化
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: Any]] else {
            
            return
        }
 

        var controllers = [UIViewController]()
        
        for dict in array! {
            let vc = viewControllers(dict: dict)
            controllers.append(vc)
        }
        
        viewControllers = controllers
    }
    
    /**
        clsName: 
        title:
        imageName:
     */
    fileprivate func viewControllers(dict: [String: Any]) -> UIViewController {
        guard let clsName = dict["clsName"] as? String,
              let title = dict["title"] as? String,
              let imageName = dict["imageName"] as? String,
              let vivistorInfo = dict["visitorInfo"] as? [String: String],
        
              /// 加上命名空间和控制器的名字，反射创建控制器
              let cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? LJBaseViewController.Type
        else {
        
            return UIViewController()
        }
        
        let vc = cls.init()
        vc.title = title
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        /// 设置前景字体属性
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 13)], for: .normal)
        vc.visitorInfoDictionary = vivistorInfo
        
        /// NavigationController的rootViewController 这个方法会调用NavigationController的pushViewController方法，将根控制器压栈到栈底，成为栈底控制器
        let nav = LJMainNavigationController(rootViewController: vc)
        
        return nav
    }
}







